
#pragma once

#include <stdio.h>
#include "Buffer.h"

//Loads file data and packs it to buffers.
class FileLoader
{
	private:
		FILE *f;
		size_t cur_offset;
	public:
		//Creates loader for given file.
		//In case of error does nothing.
		FileLoader(const char *filename)
		{
			f = fopen(filename, "r");
			cur_offset = 0;
		}
		//Loads next portion of data. In case of EOF returns NULL.
		//Note: you should call delete for returned buffer.
		Buffer<char> *loadNext()
		{
			//Is file opened?
			if (f == NULL)
				return NULL;
			//Loading.
			Buffer<char> *res = new Buffer<char>(128 * 1024);
			res->setSize(fread((void *)*res, sizeof(char), res->getMaxSize(), f));
			//Is EOF reached?
			if (res->getSize() == 0)
			{
				delete res;
				return NULL;
			}
			//Returning result.
			else
			{
				res->setOffset(cur_offset);
				cur_offset += res->getSize();
				return res;
			}
		}
		~FileLoader()
		{
			if (f != NULL)
				fclose(f);
		}
};
